package ynu.sxp.demoapp.security.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.sxp.demoapp.cart.entity.CartEntity;
import ynu.sxp.demoapp.cart.service.CartService;
import ynu.sxp.demoapp.security.dto.RegisterRO;
import ynu.sxp.demoapp.user.entity.UserEntity;
import ynu.sxp.demoapp.user.repository.UserRepository;
import ynu.sxp.demoapp.user.service.RoleService;
import ynu.sxp.demoapp.user.service.UserService;

import java.util.Optional;

@Service
public class RegisterService {
    private final UserRepository userRepository;
    private final UserService userService;
    private final RoleService roleService;
    private final CartService cartService;

    public RegisterService(UserRepository userRepository, UserService userService, RoleService roleService, CartService cartService) {
        this.userRepository = userRepository;
        this.userService = userService;
        this.roleService = roleService;
        this.cartService = cartService;
    }

    //RegisterService
    @Transactional
    public Optional<UserEntity> findByName(String username) {
        return userRepository.findByName(username);
    }

    private String generateNewUserCode(long userCount) {
        return "user" + String.format("%03d", userCount);
    }

    @Transactional
    public UserEntity register(RegisterRO registerRO) {
        Optional<UserEntity> existingUser = findByName(registerRO.getUsername());
        if (existingUser.isPresent()) {
            throw new RuntimeException("用户名已被使用！");
        }

        UserEntity userEntity = new UserEntity();
        userEntity.setCode(generateNewUserCode(userRepository.count() + 1));
        userEntity.setName(registerRO.getUsername());
        userEntity.setPassword(registerRO.getPassword());

        userService.addUser(userEntity);
        userService.addRoleToUser(userEntity.getId(), roleService.addRole(userEntity.getName()).getId());

        //为新用户创建购物车
        CartEntity cart = cartService.createCart(userEntity.getId());
        System.out.println(cart.getId());

        return userEntity;
    }
}
